package aad.storyboard.model;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;

import android.graphics.Paint;

public class ParticlePool{
	 
	  private ArrayList<Particle> particles;
	  public static ParticlePool inst=new ParticlePool();
	  private int x, y;					
	  private int size;
	  private int color;
	  
	  private long expTime= 120000; // 2 min;
	  private ArrayList <Particle> pool;

	  private Hashtable<Particle, Long> inUse=new Hashtable<Particle, Long>();
	  private Hashtable<Particle, Long>  available=new Hashtable<Particle, Long>();
	  

	  private ParticlePool() {
	    super(); 
	      
	  }

	 
	  protected ArrayList <Particle> create(int number, int x, int y, int color) {  
	      System.out.println("Creating particles");
		  this.particles = new ArrayList<Particle>();
		 	for (x=0; x<=number; x++) {
				Particle p = new Particle(x, y, color);
				particles.add(p);
			}
	     
	      return particles;
	    
	  }

	
	public void expire(Particle o) {
	o=null;		
	}

	public static ParticlePool getInstance() {
		
		return inst;
	}
	
	
	public synchronized ArrayList <Particle> checkOut(int number, int x, int y, int color) {
	    long now = System.currentTimeMillis();
	    int missingnumber=0;
	    Particle t=null;
	   	    
	    if (available.size() >= number&&available.size()>0) {
	      Enumeration<Particle> e = available.keys();
	      	while (e.hasMoreElements()) {
	      		t = e.nextElement();
	      		if ((now - available.get(t)) > expTime) {
	      			// object has expired
	      			available.remove(t);
	      			expire(t);
	      			t = null;
	      		} 
	      		else {
	      			t.setColor(color);
	      			t.setPosX(x);
	      			t.setPosY(y);
	      			t.setPaint(new Paint(this.color));
	      			available.remove(t);
	      			inUse.put(t, now);
	      			pool.add(t);	      			
	      		} 
	      	}	
	      	return pool;
	    }
	    // no objects available, create a new one
	    else
	    	{
	    	missingnumber=number-available.size();
	    	pool = create(missingnumber, x,y, color);
	    	for (Particle p: pool)
	    	inUse.put(p, now);
	    	return (pool);
	    	}
	  }
	  
	  	  
	  public synchronized void checkIn(ArrayList <Particle> list) {
		     for (Particle obj:list)
		     {
		    	 inUse.remove(obj);
		    	 available.put(obj, System.currentTimeMillis());
		     }
	  }
	  
}

